package com.bugstack.trigger.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bugstack.domain.activity.model.entity.DeliveryOrderEntity;
import com.bugstack.domain.activity.service.quota.IRaffleAccountQuotaService;
import com.bugstack.domain.credit.event.CreditAdjustSuccessEvent;
import com.bugstack.types.enums.ResponseCode;
import com.bugstack.types.event.BaseEvent;
import com.bugstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: czb
 * @Description: TODO
 * @DateTime: 2025/4/17 15:21
 **/
@Slf4j
@Component
public class CreditAdjustSuccessCustomer {

    @Value("${spring.rabbitmq.topic.send_credit_adjust}")
    private String topic;
    @Resource
    private IRaffleAccountQuotaService raffleAccountQuotaService;


    @RabbitListener(queuesToDeclare = @Queue("send_credit_adjust"))
    public void receiveCreditAdjustSuccessEvent(String message) {
        try {
            log.info("监听积分账户调整成功消息，进行交易商品发货 topic: {} message: {}", topic, message);
            BaseEvent.EventMessage<CreditAdjustSuccessEvent.CreditAdjustSuccessMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<CreditAdjustSuccessEvent.CreditAdjustSuccessMessage>>() {
            }.getType());
            CreditAdjustSuccessEvent.CreditAdjustSuccessMessage creditAdjustSuccessMessage = eventMessage.getData();
            // 积分发货
            DeliveryOrderEntity deliveryOrderEntity = new DeliveryOrderEntity();
            deliveryOrderEntity.setUserId(creditAdjustSuccessMessage.getUserId());
            deliveryOrderEntity.setOutBusinessNo(creditAdjustSuccessMessage.getOutBusinessNo());
            raffleAccountQuotaService.updateOrder(deliveryOrderEntity);
        }catch (AppException e){
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听积分账户调整成功消息，进行交易商品发货，消费重复 topic: {} message: {}", topic, message, e);
                return;
            }
            throw e;
        }catch (Exception e) {
            log.error("监听积分账户调整成功消息，进行交易商品发货失败 topic: {} message: {}", topic, message, e);
            throw e;
        }
    }
}
